package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.result.Result;
import com.sky.service.AddressBookService;
import com.sky.mapper.AddressBookMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
* @author MrWang
* @description 针对表【address_book(地址簿)】的数据库操作Service实现
* @createDate 2023-10-25 20:54:12
*/
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook>
    implements AddressBookService{

    @Autowired
    private AddressBookMapper addressBookMapper;
    @Override
    public Result addressBookList() {
        List<AddressBook> addressBooks = addressBookMapper.selectList(null);
        return Result.success(addressBooks);
    }

    //新增地址
    @Override
    public Result saveAddressBook(AddressBook addressBook) {
        addressBook.setUserId(BaseContext.getCurrentId());
        addressBookMapper.insert(addressBook);
        return Result.success();
    }

    //根据id删除地址
    @Override
    public Result deleteAddressBookById(String id) {
        addressBookMapper.deleteById(id);
        return Result.success();
    }

    //根据id查询地址
    @Override
    public Result getAddressBookById(String id) {
        AddressBook addressBook = addressBookMapper.selectById(id);
        return Result.success(addressBook);
    }

    //根据id修改地址
    @Override
    public Result updateAddressBookById(AddressBook addressBook) {
        addressBookMapper.updateById(addressBook);
        return Result.success();
    }

    //设置默认地址
    @Transactional
    @Override
    public Result setDefaultAddressBook(AddressBook addressBook) {
        //1.先解绑之前的默认地址
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<AddressBook>()
                .eq(AddressBook::getIsDefault,1);
        AddressBook addressBook1 = addressBookMapper.selectOne(queryWrapper);
        if (addressBook1 != null){
            addressBook1.setIsDefault(0);
            addressBookMapper.updateById(addressBook1);
        }
        //绑定现在的默认地址
        addressBook.setIsDefault(1);
        addressBookMapper.updateById(addressBook);

        return Result.success();
    }

    //查询默认地址
    @Override
    public Result getDefaultAddressBook() {
        LambdaQueryWrapper<AddressBook> queryWrapper = new LambdaQueryWrapper<AddressBook>()
                .eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookMapper.selectOne(queryWrapper);

        return Result.success(addressBook);
    }


}




